package com.yonyou.pmclouds.basecom.bp.processor;

import com.yonyou.pmclouds.basecom.billstatus.BillStatusConst;
import com.yonyou.pmclouds.basecom.entity.Entity;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.basecom.impl.BillDrivenImpl;
import com.yonyou.pmclouds.basecom.util.BeanHelper;
import com.yonyou.pmclouds.basecom.util.CommonFieldConst;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 单据驱动后处理期，目前只有综合验收有单据驱动
 *
 * @author mapeif
 */
@Component
public class BillDrivenProcessorFactory {
    //  用来调用nc的接口
    @Autowired
    private BillDrivenImpl.BillDrivenInvoker invoker;

    public <T extends Entity> BillDrivenProcessor<T> getBillDrivenProcessor(String billType, AdditionalInfoToDriven<T> extractor) {
        return new BillDrivenProcessor<>(billType, extractor);
    }

    /**
     * 用来给各个业务传递可能需要的额外信息
     */
    public interface AdditionalInfoToDriven<T extends Entity> {
        Map<String, Object> extractAdditionalInfo(T vo, T orig) throws BusinessException;
    }

    public class BillDrivenProcessor<T extends Entity> implements SingleProcessor<T> {
        private String billType;
        private AdditionalInfoToDriven<T> extractor;

        private BillDrivenProcessor(String billType, AdditionalInfoToDriven<T> extractor) {
            this.billType = billType;
            this.extractor = extractor;
        }

        @Override
        public void process(T vo, T orig) throws BusinessException {
            byte status = BeanHelper.getProperty(vo, CommonFieldConst.BILLSTATUS) == null ?
                    (byte) 0 : (byte) BeanHelper.getProperty(vo, CommonFieldConst.BILLSTATUS);
            if (status != BillStatusConst.COMMON_APPROVED_STATUS) {
                return;
            }
            BillDrivenImpl.DrivenInvokeInfo info = new BillDrivenImpl.DrivenInvokeInfo();
            info.setPkBill((String) vo.pkFiledValue());
            info.setBillType(billType);
            String tenant = (String) BeanHelper.getProperty(vo, CommonFieldConst.PK_TENANT);
            if (tenant == null) {
                tenant = (String) BeanHelper.getProperty(vo, CommonFieldConst.PKTENANT);
            }
            info.setPkTenant(tenant);
            String project = (String) BeanHelper.getProperty(vo, CommonFieldConst.PK_PROJECT);
            if (project == null) {
                project = (String) BeanHelper.getProperty(vo, CommonFieldConst.PKPROJECT);
            }
            info.setPkProject(project);
            Map<String, Object> addInfo = null;
            if (extractor != null) {
                addInfo = extractor.extractAdditionalInfo(vo, orig);
            }
            invoker.invokeDriven(info, BillDrivenImpl.ACTION_APPROVED, addInfo);
        }
    }
}
